package com.zyk.leetcode;

import java.util.HashMap;

/**
 * @author zhangsan
 * @date 2021/4/6 15:12
 */
public class C1 {

    // https://leetcode-cn.com/problems/two-sum/
    // 暴力解 O(N^)
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    // 枚举 nums[i] 和多少能组成target
    // 遍历一边数组, 中途遇到答案直接返回, 在这一遍中把后序数字都放到了map中.
    public static int[] twoSum2(int[] nums, int target) {
        HashMap<Integer, Integer> indexMap = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            if(indexMap.containsKey(target - nums[i])) {
                return new int[]{ i, indexMap.get(target-nums[i]) };
            }
            indexMap.put(nums[i], i);
        }
        return new int[0];
    }


    // for test
    public static void main(String[] args) {

    }

}
